window.adminPageIndex = 0;
window.adminPageSize = 8;
window.adminFileId = null;
window.adminFileName = null;
window.adminFileDescription = null;
window.adminUpdateFileCategoryKey = null;
window.adminUpdateFileCategoryName = null;


//管理员登录绑定回车事件
document.onkeydown = function (ev){
    if (ev.keyCode == 13){
        adminLoginButton();
    }
}
$(function (){
    // 管理员左侧树结构展示
        $(".list-group-item").click(function() {
            if ($(this).find("ul")) {
                $(this).toggleClass("tree-closed");
                if ($(this).hasClass("tree-closed")) {
                    $("ul", this).hide("fast");
                } else {
                    $("ul", this).show("fast");
                }
            }
        });



})

function adminLoginButton(){
    let username = $("#admin_login_username").val();
    let password = $("#admin_login_password").val();
    if (username == ''){
        layer.msg("请输入管理员账户名!");
        return;
    }
    if (password == ''){
        layer.msg("请输入密码!");
        return;
    }
    // if (username == 'admin' && password == 'admin'){
    //     window.location.href='main.html';
    //     return;
    // }
    if (username != '' && password != ''){
        $.ajax({
            url:'/admin/to/login',
            type:'get',
            async:false,
            data:{
                username:username,
                password:password
            },
            datatype:'json',
            success:function (data){
                if (data == "FAILED"){
                    // layer.msg("账号与密码不匹配!");
                    layer.msg("该账户没有管理员权限");
                }
                if (data == "SUCCESS"){
                    window.location.href='index.html';
                }
            }
        })
    }
}

// 管理员退出
function adminLogout(){
    layer.confirm("确认退出管理员系统吗?",function (){
        $.ajax({
            url: '/admin/logout',
            type: 'get',
            async:false,
            datatype: 'json',
            success:function (data){
                if (data == "SUCCESS"){
                    window.location.href='login.html';
                    window.location.reload();
                }
                if (data == "FAILED"){
                    layer.msg("服务器内部错误请稍后再试");
                }
            }
        })


    })
}

//生成用户分页列表
function generateConsumerList(){
    let pageInfo = getConsumerPageInfo();
    fillConsumerListTableBody(pageInfo);
}

//获取用户数据
function getConsumerPageInfo(){
    let ajaxResult = $.ajax({
        url:'/admin/get/consumer/list',
        type:'post',
        async:false,
        data:{
            pageIndex:adminPageIndex,
            pageSize:adminPageSize,
        },
        datatype:'json',
    });

    // 判断当前响应状态码是否为200
    let statusCode = ajaxResult.status;
    // 如果当前响应状态码不是200，说明发生了错误或其他意外情况，显示提示消息，让当前函数停止执行
    if(statusCode != 200) {
        layer.msg("失败！响应状态码="+statusCode+" 说明信息="+ajaxResult.statusText);
        return null;
    }
    // 如果响应状态码是200，说明请求处理成功，获取pageInfo
    let resultEntity = ajaxResult.responseJSON;
    // 从resultEntity中获取result属性
    var result = resultEntity.result;

    // 判断result是否成功
    if(result == "FAILED") {
        layer.msg(resultEntity.message);
        return null;
    }

    // 确认result为成功后获取pageInfo
    let pageInfo = resultEntity.data;
    //console.log(pageInfo)

    // 返回pageInfo
    return pageInfo;
}

function fillConsumerListTableBody(pageInfo){
    // 清除tbody中的旧的内容
    $("#admin-consumer-list").empty();

    // 这里清空是为了让没有搜索结果时不显示页码导航条
    $("#adminPagination").empty();

    // 判断pageInfo对象是否有效
    if(pageInfo == null || pageInfo == undefined || pageInfo.size == null || pageInfo.size == 0) {
        $("#file-tbody").append("<tr><td colspan='8'><p>抱歉！没有查询到您搜索的数据!</p></td></tr>")
        return ;
    }
    let list = pageInfo.records;
    for (let i=0;i<list.length;i++){
        let tbody = $("#admin-consumer-list");
        let number = "<td><input type='checkbox' id='"+list[i].id+"'>"+'&nbsp;'+(i+1)+"</td>";
        let username = "<td>"+list[i].username+"</td>";
        let password = "<td>******</td>";
        let nick = "<td>"+list[i].nick+"</td>";
        let phone = "<td>"+list[i].phone+"</td>";
        let isLive = "<td>"+list[i].isLive+"</td>";
        let registerTime = "<td>"+list[i].registerTime.substring(0,10)+"</td>"
        let check = "<button type='button' class='btn btn-success btn-xs'>" +
            "<i class='glyphicon glyphicon-check'></i></button>";
        let pencil = "<button type='button' class='btn btn-primary btn-xs' onclick=adminUpdateConsumerButton(" +
            "'"+list[i].username+"','"+list[i].nick+"','"+list[i].phone+"','"+list[i].isLive+"')>" +
            "<i class='glyphicon glyphicon-pencil'></i></button>"
        let remove = "<button type='button' onclick=adminDeleteConsumer('"+list[i].id+"','"+list[i].nick+"') class='btn btn-danger btn-xs'>" +
            "<i class='glyphicon glyphicon-remove'></i></button>";
        let normalConsumer = "<span style='color: green'>正常</span>";
        let disabledConsumer = "<span style='color: red'>禁用</span>";
        tbody.append("<tr>");
        tbody.append(number);
        tbody.append(username);
        tbody.append(password);
        tbody.append(nick);
        tbody.append(phone);
        tbody.append(isLive == "<td>1</td>" ? normalConsumer : disabledConsumer);
        tbody.append(registerTime);
        tbody.append("<td>"+check+pencil+remove+"</td>");
    }
    // 生成分页导航条
    generateNavigatorConsumerList(pageInfo);
}

function generateNavigatorConsumerList(pageInfo){
    // 获取总记录数
    var totalRecord = pageInfo.size;

    // 声明相关属性
    var properties = {
        "num_edge_entries": 3,
        "num_display_entries": 5,
        "callback": paginationCallBackConsumerList,
        "items_per_page": adminPageSize,
        "current_page": adminPageIndex - 1,
        "prev_text": "上一页",
        "next_text": "下一页"
    };

    // 调用pagination()函数
    $("#adminPagination").pagination(totalRecord, properties);
}

function paginationCallBackConsumerList(pageIndex){
    // 修改window对象的pageNum属性
    window.adminPageIndex = pageIndex + 1;
    // 调用分页函数
    generateConsumerList();
    // 取消页码超链接的默认行为
    return false;
}

//管理员添加用户
function adminAddConsumer(){
    if ($("#admin_add_username").val()==''){
        layer.msg("账户名不能为空");
        return;
    }
    if ($("#admin_add_password").val()==''){
        layer.msg("密码不能为空");
        return;
    }
    if ($("#admin_add_nick").val()==''){
        layer.msg("昵称不能为空");
        return;
    }
    if ($("#admin_add_phone").val()==''){
        layer.msg("手机号不能为空");
        return;
    }
    let usernameFlag = true;
    let nickFlag = true;
    let phoneFlag = true;
    $.ajax({
        url:'/get/username',
        type:'get',
        datatype:'json',
        data:{
            register_username: $("#admin_add_username").val()
        },
        success:function (data){
            if (data == "FAILED"){
                layer.msg("用户名已存在!");
                usernameFlag =false;
            }
            if (usernameFlag){
                $.ajax({
                    url:'/judge/phone',
                    type:'get',
                    datatype:'json',
                    async:false,
                    data:{
                        phone:$("#admin_add_phone").val()
                    },
                    success:function (data){
                        if (data == "FAILED"){
                            layer.msg("手机号已被注册!");
                            phoneFlag=false;
                        }
                        if (phoneFlag){
                            $.ajax({
                                url:'/get/nick',
                                type:'get',
                                datatype:'json',
                                async:false,
                                data:{
                                    nick:$("#admin_add_nick").val(),
                                },
                                success:function (data){
                                    if (data == "FAILED"){
                                        layer.msg("昵称已被占用！");
                                        nickFlag = false;
                                    }
                                    if (nickFlag){
                                        $.ajax({
                                            url:'/to/register/consumer',
                                            type:'post',
                                            async:false,
                                            data:{
                                                username:$("#admin_add_username").val(),
                                                password: $("#admin_add_password").val(),
                                                nick: $("#admin_add_nick").val(),
                                                phone: $("#admin_add_phone").val()
                                            },
                                            datatype:'json',
                                            success:function (data){
                                                if (data == "SUCCESS"){
                                                    $("#adminAddConsumerModal").modal("hide");
                                                    generateConsumerList();
                                                    layer.msg("添加成功!");
                                                }else {
                                                    layer.msg("添加失败,服务器错误");
                                                }
                                            }
                                        })
                                    }
                                }
                            })
                        }
                    }
                })
            }
        }
    })
}

//管理员修改用户按钮
function adminUpdateConsumerButton(username,nick,phone,isLive){
    $("#adminUpdateConsumerModal").modal("show");
    $("#admin_update_username").val(username);
    $("#admin_update_nick").val(nick);
    $("#admin_update_phone").val(phone);
    if (isLive==1){
        $("#normal").prop("checked",true);
    }else {
        $("#disabled").prop("checked",true);
    }
}

//管理员修改用户
function adminUpdateConsumer(){
    $.ajax({
        url:'/admin/update/consumer',
        type:'post',
        datatype:'json',
        data:{
            username:$("#admin_update_username").val(),
            password:$("#admin_update_password").val(),
            nick:$("#admin_update_nick").val(),
            phone:$("#admin_update_phone").val(),
            isLive:$("#consumerIsLive input[name=isLive]:checked").val()
        },
        success:function (data){
            console.log(data);
            if (data == "SUCCESS"){
                $("#adminUpdateConsumerModal").modal("hide");
                generateConsumerList();
                layer.msg("修改成功!");
            }
            if (data == "FAILED"){
                layer.msg("修改失败,请检查参数");
            }
        }
    })
}

//管理员删除用户
function adminDeleteConsumer(id,nick){
    layer.confirm("确认删除 "+nick+" 该用户吗?",function (){
        $.ajax({
            url:'/delete/consumer',
            type:'get',
            data:{
                id:id
            },
            datatype:"json",
            success:function (data){
                if (data == "SUCCESS"){
                    layer.msg("删除成功!");
                    generateConsumerList();
                }
                if (data == "FAILED"){
                    layer.msg("删除失败!");
                }
            }
        })


    })
}


//2.获取文件列表全部数据
function adminGenerateFileList() {
    // 1.获取分页数据
    var pageInfo = getFileListPageInfo();

    // 2.填充表格
    fillFileListTableBody(pageInfo);
}

//2.1获取文件列表分页数据
function getFileListPageInfo(){
    let ajaxResultFileList = $.ajax({
        url:'/get/file/list',
        type:'get',
        data:{
            pageIndex:adminPageIndex,
            pageSize:adminPageSize,
        },
        async:false, //此时的ajax请求必须为同步
        datatype:'json',
    });
    // 判断当前响应状态码是否为200
    let statusCode = ajaxResultFileList.status;
    // 如果当前响应状态码不是200，说明发生了错误或其他意外情况，显示提示消息，让当前函数停止执行
    if(statusCode != 200) {
        layer.msg("失败！响应状态码="+statusCode+" 说明信息="+ajaxResultFileList.statusText);
        return null;
    }
    // 如果响应状态码是200，说明请求处理成功，获取pageInfo
    let resultEntity = ajaxResultFileList.responseJSON;
    // 从resultEntity中获取result属性
    var result = resultEntity.result;

    // 判断result是否成功
    if(result == "FAILED") {
        layer.msg(resultEntity.message);
        return null;
    }

    // 确认result为成功后获取pageInfo
    let pageInfo = resultEntity.data;
    //console.log(pageInfo)

    // 返回pageInfo
    return pageInfo;
}

//2.2填充全部文件列表表格
function fillFileListTableBody(pageInfo){
    // 清除tbody中的旧的内容
    $("#admin-file-tbody").empty();

    // 这里清空是为了让没有搜索结果时不显示页码导航条
    $("#adminFilePagination").empty();

    // 判断pageInfo对象是否有效
    if(pageInfo == null || pageInfo == undefined || pageInfo.size == null || pageInfo.size == 0) {
        $("#admin-file-tbody").append("<tr><td colspan='7'><p>抱歉！没有查询到您搜索的数据!</p></td></tr>")
        return ;
    }


    let fileList = pageInfo.records;
    for (let i=0;i<fileList.length;i++){
        let number = "<td>"+(i+1)+"</td>";
        let fileName = "<td>"+fileList[i].fileName+"</td>";
        let fileCategoryKey = "<td>"+fileList[i].fileCategoryKey+"</td>";
        let fileAuthor = "<td>"+fileList[i].fileAuthor+"</td>";
        let dateTime = "<td>"+fileList[i].fileCreateTime.substring(0,10)+"</td>"
        let fileDownloadTimes = "<td>"+fileList[i].fileDownloadTimes+"</td>"
        let downloadFile = "<a class='btn btn-primary' type='button' onclick=downloadFileClick('"+fileList[i].fileName+"','"+fileList[i].fileAuthor+"')>下载</a>"
        let deleteFile = "<a class='btn btn-danger' type='button' onclick=deleteFileClick('"+fileList[i].fileName+"','"+fileList[i].fileAuthor+"','"+fileList[i].fileId+"','"+fileList[i].fileCategoryKey+"')>删除</a>"
        let updateFile = "<button type='button' class='btn btn-success' onclick=adminUpdateFileButton('"+fileList[i].fileId+"','"+fileList[i].fileName+"','"+fileList[i].fileCategoryKey+"','"+fileList[i].description+"')>修改</button>"
        let operate = "<td>"+updateFile+downloadFile+deleteFile+"</td>"

        let tr = "<tr data-widget='expandable-table' aria-expanded='false'>"+
            number+fileName+fileCategoryKey+fileAuthor+dateTime+fileDownloadTimes
            +operate+"</tr>"
        $("#admin-file-tbody").append(tr);
        $("#admin-file-tbody").append("<tr class='expandable-body d-none'>" +
            "<td colspan='7'><p style='display: none;'>"+"文件描述："+fileList[i].description+"</p></td>")
    }
    // 生成分页导航条
    generateNavigatorFileList(pageInfo);
}

//2.3生成全部文件列表导航条
function generateNavigatorFileList(pageInfo){
    // 获取总记录数
    let totalRecord = pageInfo.size;

    // 声明相关属性
    let properties = {
        "num_edge_entries": 3,
        "num_display_entries": 5,
        "callback": paginationCallBackFileList,
        "items_per_page": adminPageSize,
        "current_page": adminPageIndex-1,
        "prev_text": "上一页",
        "next_text": "下一页"
    };

    // 调用pagination()函数
    $("#adminFilePagination").pagination(totalRecord, properties);
}

//2.4全部文件列表翻页的回调函数
function paginationCallBackFileList(pageIndex){
    // 修改window对象的pageNum属性
    window.adminPageIndex = pageIndex + 1;
    // 调用分页函数
    adminGenerateFileList();
    // 取消页码超链接的默认行为
    return false;
}

//文件下载及判断
function downloadFileClick(fileName,fileAuthor){
    var isDownloadSuccess = false;
    if (false){
        layer.msg("请先登录!");
        return;
    }else {
        //window.location.href='/download/file/?filename='+fileName+'&fileAuthor='+fileAuthor;
        window.location.href='https://mask4-boot.oss-cn-shanghai.aliyuncs.com/mask4-file-upload/'+fileName;
        isDownloadSuccess = true;
    }
    if (isDownloadSuccess){
        $.ajax({
            url:'/download/file/success/echo',
            type:'post',
            data:{
                fileName:fileName,
                fileAuthor:fileAuthor
            },
            async:false,
            datatype:'json',
            success:function (data){
                if (data == "SUCCESS"){
                    console.log(data)
                    layer.msg("下载成功!");
                    adminGenerateFileList();
                }
                if (data == "FAILED"){
                    layer.msg("下载失败!请稍后再试");
                }
            }
        })
    }

}

//文件删除及权限控制
function deleteFileClick(fileName,fileAuthor,fileId,fileCategoryKey){
    // if (nick == null){
    //     layer.msg("请先登录！");
    //     return;
    // }
    // if (nick != fileAuthor){
    //     layer.msg("您没有删除该文件的权限");
    //     return;
    // }
    if (true){

        layer.confirm("尊敬的管理员"+"！确认删除 "+fileName+" 该文件吗?",function (){
            $.ajax({
                url: '/to/delete/file',
                type: 'post',
                async: false,
                data: {
                    fileId: fileId,
                    fileCategoryKey: fileCategoryKey,
                    fileName: fileName
                },
                datatype: 'json',
                success:function (data){
                    if (data == "SUCCESS"){
                        layer.msg("删除成功!");
                        adminGenerateFileList();
                    }
                    if (data == "FAILED"){
                        layer.msg("请求超时!请稍后再试");
                    }
                }
            })
        })
    }
}

//管理员修改文件
function adminUpdateFileButton(fileId,fileName,fileCategory,description){
    $("#adminUpdateFileModal").modal("show");
    $("#admin_update_filename").val(fileName);
    $("#updateDescription").val(description);
    window.adminFileId = fileId;
}

function adminUpdateFile(){
    $.ajax({
        url:'/admin/update/file',
        type:'get',
        data:{
            fileId: window.adminFileId,
            fileName:$("#admin_update_filename").val(),
            description:$("#updateDescription").val()
        },
        datatype:'json',
        success:function (data){
            if (data == "SUCCESS"){
                $("#adminUpdateFileModal").modal("hide");
                adminGenerateFileList();
                layer.msg("修改成功");
            }
            if (data == "FAILED"){
                layer.msg("修改失败");
            }
        }
    })
}

function fileUploadButton(){
    getFileCategory();
}

function getFileCategory(){
    $.ajax({
        url:'/get/file/category',
        type:'get',
        datatype:'json',
        success:function (data){
            let result = data.result;
            if (result == "SUCCESS"){
                let fileCategory = data.data;
                let select = $("#categoryKey");
                select.empty();
                for (let i=0;i<fileCategory.length;i++){
                    select.append("<option value='"+fileCategory[i].fileCategoryKey+"'>"+fileCategory[i].fileCategoryName+"</option>")
                }
                // let updateSelect = $("#updateCategoryKey");
                // updateSelect.empty();
                // for (let i=0;i<fileCategory.length;i++){
                //     updateSelect.append("<option value='"+fileCategory[i].fileCategoryKey+"'>"+fileCategory[i].fileCategoryName+"</option>")
                // }

            }
        }
    })
}


//文件上传表单异步请求
$(document).ready(function () {
    $("#uploadForm").ajaxForm(function () {

    });
});
//文件上传
function uploadFile() {
    var fileVal = $("#icon").val();
    var categoryKey = $("#categoryKey option:selected").val();
    var iconSize = document.getElementById('icon').files[0];
    var fileMaxSize = 200 * 1024 * 1024;  //文件最大为200M
    if (fileVal == "") {
        layer.msg("请添加上传文件!");
        return;
    }
    if (categoryKey == "") {
        layer.msg("请选择上传文件分类!");
        return;
    }
    if (iconSize.size > fileMaxSize) {
        console.log(iconSize.size);
        //console.log("test");
        layer.msg("上传文件不得大于200M");
        return;
    }else {
        let formData = new FormData();
        formData.append("icon",$("#icon")[0].files[0]);
        formData.append("categoryKey",$("#categoryKey option:selected").text());
        formData.append("description",$("#description").val());
        formData.append("fileAuthor","管理员");
        $.ajax({
            type:'post',
            enctype:'multipart/form-data',
            url: '/upload',
            data:formData,
            cache:false,
            processData:false,
            contentType:false,
            async:false,
            success:function (data){
                console.log(data);

            },
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                if (xhr.upload) {
                    $("#icon").attr("disabled",true);
                    $("#uploadFormData").attr("disabled",true);
                    //处理进度条的事件
                    $("#uploadModal").modal('show');

                    xhr.upload.addEventListener("progress", progressHandle, false);
                    //加载完成的事件
                    xhr.addEventListener("load", completeHandle, true);
                    //加载出错的事件
                    xhr.addEventListener("error", failedHandle, true);
                    //加载取消的事件
                    xhr.addEventListener("abort", canceledHandle, true);
                    //开始显示进度条
                    showProgress(e);
                    return xhr;
                }
            }
        },'json')
    }
}
var start = 0;
//显示进度条的函数
function showProgress() {
    start = new Date().getTime();
    $(".progress-body").css("display", "block");
    $('.progress-body .progress-info').html("上传文件中...");
    //点击上传进度条和文字显示
    $(".progress-body progress").show();
    $(".progress-body percentage").show();


    $("#uploadModal").modal('show');
}
//隐藏进度条的函数
function hideProgress() {
    $("#uploadFormData").val('');
    $('.progress-body .progress-speed').html("0 M/S, 0/0M");
    $('.progress-body percentage').html("0%");
    $('.progress-body .progress-info').html("请选择文件并点击上传文件按钮");
    $("#icon").attr("disabled",false);
    $("#uploadFormData").attr("disabled",false);
    $(".progress-body").css("display", "none");
}
//进度条更新
function progressHandle(e) {
    //点击上传进度条和文字显示
    $(".progress-body progress").show();
    $(".progress-body percentage").show();

    //显示进度百分数
    $('.progress-body progress').attr({value: e.loaded, max: e.total});
    //计算进度数
    var percent = e.loaded / e.total * 100;
    //需要根据网速计算需要花费的时间
    var time = ((new Date().getTime() - start) / 1000).toFixed(3);
    if(time == 0){
        time = 1;
    }
    //显示上传速度，和上传文件大小及进度
    $('.progress-body .progress-speed').html(((e.loaded / 1024) / 1024 / time).toFixed(2) + "M/S, " + ((e.loaded / 1024) / 1024).toFixed(2) + "/" + ((e.total / 1024) / 1024).toFixed(2) + " MB. ");
    //更新上传进度数
    $('.progress-body percentage').html(percent.toFixed(2) + "%");
    //更新进度条宽度
    $(".progress-body progress").width(percent.toFixed(0));
    if (percent == 100) {
        $('.progress-body .progress-info').html("上传完成,后台正在处理...");
    } else {
        $('.progress-body .progress-info').html("文件上传中...");
    }
};
//上传完成处理函数
function completeHandle(e) {
    //$('.progress-body .progress-info').html("上传文件中...");
    setTimeout(hideProgress, 2000);
    $("#uploadModal").modal('hide');
    layer.msg("上传成功!");
    generatePageFileList();

};
//上传出错处理函数
function failedHandle(e) {
    $('.progress-body .progress-info').html("上传文件出错, 服务不可用或文件过大。");
    setTimeout(hideProgress, 2000);
};
//上传取消处理函数
function canceledHandle(e) {
    $('.progress-body .progress-info').html("上传文件取消。");
    setTimeout(hideProgress, 2000);
};

//管理员添加文件分类
function adminAddFileCategory(){
    if ($("#admin_add_file_category_key").val()==''){
        layer.msg("文件id不为空!");
        return;
    }
    if ($("#admin_add_file_category_name").val()==''){
        layer.msg("文件名不为空!");
        return;
    }
    $.ajax({
        url:'/admin/add/file/category',
        type:'post',
        data:{
            "fileCategoryKey": $("#admin_add_file_category_key").val(),
            "fileCategoryName": $("#admin_add_file_category_name").val()
        },
        datatype:'json',
        success:function (data){
            if (data == "SUCCESS"){
                $("#adminAddFileCategoryModal").modal("hide");
                adminGenerateFileList();
                layer.msg("添加成功!");
            }
            if (data == "FAILED"){
                layer.msg("添加失败!");
            }
        }
    })
}

//管理员生成文件分类列表
function adminGenerateFileCategoryList(){
    // 1.获取分页数据
    var pageInfo = getFileCategoryListPageInfo();

    // 2.填充表格
    fillFileCategoryListTableBody(pageInfo);
}

//2.1获取文件分类列表分页数据
function getFileCategoryListPageInfo(){
    let ajaxResultFileList = $.ajax({
        url:'/admin/get/file/category',
        type:'get',
        data:{
            pageIndex:adminPageIndex,
            pageSize:adminPageSize,
        },
        async:false, //此时的ajax请求必须为同步
        datatype:'json',
    });
    // 判断当前响应状态码是否为200
    let statusCode = ajaxResultFileList.status;
    // 如果当前响应状态码不是200，说明发生了错误或其他意外情况，显示提示消息，让当前函数停止执行
    if(statusCode != 200) {
        layer.msg("失败！响应状态码="+statusCode+" 说明信息="+ajaxResultFileList.statusText);
        return null;
    }
    // 如果响应状态码是200，说明请求处理成功，获取pageInfo
    let resultEntity = ajaxResultFileList.responseJSON;
    // 从resultEntity中获取result属性
    var result = resultEntity.result;

    // 判断result是否成功
    if(result == "FAILED") {
        layer.msg(resultEntity.message);
        return null;
    }

    // 确认result为成功后获取pageInfo
    let pageInfo = resultEntity.data;
    //console.log(pageInfo)

    console.log(pageInfo)
    // 返回pageInfo
    return pageInfo;
}

//2.2填充全部文件分类列表表格
function fillFileCategoryListTableBody(pageInfo){
    // 清除tbody中的旧的内容
    $("#admin-file-category-tbody").empty();

    // 这里清空是为了让没有搜索结果时不显示页码导航条
    $("#adminFileCategoryPagination").empty();

    // 判断pageInfo对象是否有效
    if(pageInfo == null || pageInfo == undefined || pageInfo.size == null || pageInfo.size == 0) {
        $("#admin-file-category-tbody").append("<tr><td colspan='4'><p>抱歉！没有查询到您搜索的数据!</p></td></tr>")
        return;
    }


    let fileList = pageInfo.records;
    for (let i=0;i<fileList.length;i++){
        let number = "<td>"+(i+1)+"</td>";
        let fileCategoryKey = "<td>"+fileList[i].fileCategoryKey+"</td>";
        let fileCategoryName = "<td>"+fileList[i].fileCategoryName+"</td>";
        let deleteFile = "<a class='btn btn-danger' type='button' onclick=deleteFileCategoryButton('"+fileList[i].fileCategoryKey+"','"+fileList[i].fileCategoryName+"')>删除</a>"
        let updateFile = "<button type='button' class='btn btn-success' onclick=adminUpdateFileCategoryButton('"+fileList[i].fileCategoryKey+"','"+fileList[i].fileCategoryName+"')>修改</button>"
        let operate = "<td>"+updateFile+deleteFile+"</td>"

        let tr = "<tr data-widget='expandable-table' aria-expanded='false'>"+
            number+fileCategoryKey+fileCategoryName+operate+"</tr>"
        $("#admin-file-category-tbody").append(tr);
        // $("#admin-file-category-tbody").append("<tr class='expandable-body d-none'>" +
        //     "<td colspan='4'><p style='display: none;'>"+"文件描述："+fileList[i].description+"</p></td>")
    }
    // 生成分页导航条
    generateNavigatorFileCategoryList(pageInfo);
}

//2.3生成全部文件分类列表导航条
function generateNavigatorFileCategoryList(pageInfo){
    // 获取总记录数
    let totalRecord = pageInfo.size;

    // 声明相关属性
    let properties = {
        "num_edge_entries": 3,
        "num_display_entries": 5,
        "callback": paginationCallBackFileCategoryList,
        "items_per_page": adminPageSize,
        "current_page": adminPageIndex-1,
        "prev_text": "上一页",
        "next_text": "下一页"
    };

    // 调用pagination()函数
    $("#adminFileCategoryPagination").pagination(totalRecord, properties);
}

//2.4全部文件分类列表翻页的回调函数
function paginationCallBackFileCategoryList(pageIndex){
    // 修改window对象的pageNum属性
    window.adminPageIndex = pageIndex + 1;
    // 调用分页函数
    adminGenerateFileCategoryList();
    // 取消页码超链接的默认行为
    return false;
}

//管理员删除文件分类
function deleteFileCategoryButton(fileCategoryKey,fileCategoryName){
    layer.confirm("确认删除 "+fileCategoryName+" 该文件分类吗?",function (){
        $.ajax({
            url:'/admin/delete/file/category',
            type:'post',
            data:{
                fileCategoryKey:fileCategoryKey
            },
            datatype:'json',
            success:function (data){
                if (data == "SUCCESS"){
                    adminGenerateFileCategoryList();
                    layer.msg("删除成功!");
                }
                if (data == "FAILED"){
                    layer.msg("删除失败!");
                }
            }
        })
    })
}

//管理员修改文件分类
function adminUpdateFileCategoryButton(fileCategoryKey,fileCategoryName){
    $("#adminUpdateFileCategoryModal").modal("show");
    $("#admin_update_file_category_key").val(fileCategoryKey)
    $("#admin_update_file_category_name").val(fileCategoryName);
    window.adminUpdateFileCategoryKey = fileCategoryKey;
    window.adminUpdateFileCategoryName = fileCategoryName;
}

function adminUpdateFileCategory(){
    if ($("#admin_update_file_category_key").val()==''){
        layer.msg("文件分类id不为空!");
        return;
    }
    if ($("#admin_update_file_category_name").val()==''){
        layer.msg("文件分类名不为空!");
        return;
    }
    $.ajax({
        url:'/admin/update/file/category',
        type:'post',
        data:{
            fileCategoryKey:$("#admin_update_file_category_key").val(),
            fileCategoryName:$("#admin_update_file_category_name").val(),
            fileCategoryOldName:window.adminUpdateFileCategoryName
        },
        datatype:'json',
        success:function (data){
            if (data == "SUCCESS"){
                $("#adminUpdateFileCategoryModal").modal("hide");
                adminGenerateFileCategoryList();
                layer.msg("修改成功!");
            }
            if (data == "FAILED"){
                layer.msg("修改失败!");
            }
        }
    })


}
